import { tagListColor } from '@/constant/tag'
import NoticeEvents from '@/event/noticeEvents'
import { addDialog } from '@/components/SpDialog/index'
import ModalDetails from '../details.vue'
import { getDictDataListAPI } from '@/views/admin/system/dict/utils/api'
import type { SysDictionaryDataType } from '@/views/admin/system/dict/utils/model'
import { getUserAllMessageAPI, readNoticeAPI } from '@/views/admin/system/notice/utils/api'
import type {
  ListByUserMessageType,
  ListUserAllMessageParams
} from '@/views/admin/system/notice/utils/model'

export function useNotice() {
  // 通知列表
  const noticeList = ref<ListByUserMessageType[]>([])
  // 消息类型字典
  const messageTypeList = ref<SysDictionaryDataType[]>([])
  // 通知列表总数
  const noticeTotal = ref(0)
  // 查询参数
  const queryNoticeParams = reactive<ListUserAllMessageParams>({
    value: '',
    pageNum: 1,
    pageSize: 5
  })

  // 获取通知列表
  function getNoticeList() {
    getUserAllMessageAPI(queryNoticeParams).then((res) => {
      noticeList.value = res.data.rows
      noticeTotal.value = res.data.total
    })
  }

  // 获取消息类型字典
  function getMessageTypeList() {
    getDictDataListAPI('system_message_type').then((res) => {
      messageTypeList.value = res.data
    })
  }

  /**
   * 获取消息类型名称
   * @param name
   * @param text
   */
  function getMessageTypeName(name: string, text?: boolean) {
    let index = 0
    const dictName = messageTypeList.value.find((item, i) => {
      index = 0
      return item.dictValue === name
    })?.dictName
    return text ? dictName : tagListColor[index]
  }

  // 查看详情
  function openDetails(data: ListByUserMessageType) {
    addDialog({
      title: `查看通知公告`,
      width: '80%',
      footer: false,
      contentRenderer: () =>
        h(ModalDetails, {
          data
        })
    })
    if (data.isRead == 0) {
      readNoticeAPI([data.id]).then(() => {
        getNoticeList()
      })
    }
  }

  // 改变通知页码
  function changeNoticePage(pageNum: number, pageSize: number) {
    queryNoticeParams.pageNum = pageNum
    queryNoticeParams.pageSize = pageSize
    getNoticeList()
  }

  onMounted(() => {
    getNoticeList()
    getMessageTypeList()
  })

  // 监听通知事件
  NoticeEvents.on('on:system:message', (data) => {
    queryNoticeParams.pageNum = 1
    getNoticeList()
  })

  return {
    noticeList,
    noticeTotal,
    queryNoticeParams,
    getMessageTypeName,
    changeNoticePage,
    openDetails
  }
}
